package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.PageResult;
import com.tanhua.model.domain.mongo.Movement;
import com.tanhua.model.domain.mysql.UserInfo;
import com.tanhua.model.domain.vo.MovementsVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lk
 * @date 2022-04-04
 */
@Service
public class ManagerService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //查询用户列表
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage<UserInfo> iPage = userInfoApi.findAll(page, pagesize);
        //拿出用户列表的所有用户信息
        List<UserInfo> records = iPage.getRecords();
        for (UserInfo record : records) {
            //判断用户是否有被冻结的操作
            String key = Constants.USER_FREEZE+record.getId();
            if (redisTemplate.hasKey(key)){
                //有则设置状态
                record.setUserStatus("2");
            }
        }

        return new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 根据id查询用户详情
     */
    public ResponseEntity findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        //查询redis中的冻结状态
        String key = Constants.USER_FREEZE + userId;
        //存在则代表用户  有操作被冻结
        if (redisTemplate.hasKey(key)){
            //设置冻结状态
            userInfo.setUserStatus("2");
        }
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 查询指定用户发布的所有视频列表
     */
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page, pagesize, uid);
    }

    /**
     * 查看动态列表
     */
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //获取动态
        PageResult result = movementApi.findByMovement(page, pagesize, uid, state);
        List<Movement> items = (List<Movement>) result.getItems();
        //获取所有动态的用户id
        List<Long> userId = CollUtil.getFieldValues(items, "userId", Long.class);
        //查询所有用户详细信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userId, null);
        //构造返回值
        List<MovementsVo> list = new ArrayList<>();
        for (Movement item : items) {
            UserInfo userInfo = userInfoMap.get(item.getUserId());
            MovementsVo init = MovementsVo.init(userInfo, item);
            list.add(init);
        }
        result.setItems(list);
        return result;
    }

    /**
     * 用户冻结
     */
    public Map userFreeze(Map params) {
        //构造redis key
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        //构造失效时间  拿出数字判断冻结时间
        Integer freezingTime = Integer.parseInt(params.get("freezingTime").toString());
        //判断冻结天数
        int day = 0;
        if (freezingTime == 1) {
            day = 3;
        } else if (freezingTime == 2) {
            day = 7;
        }
        //保存数据到redis
        String value = JSON.toJSONString(params); //将数据转换为json格式
        if (day > 0) {                       //键   值      失效时间   时间单位
            redisTemplate.opsForValue().set(key, value, day, TimeUnit.DAYS);
        } else {
            redisTemplate.opsForValue().set(key, value); //不设置失效时间则永不失效
        }
        Map map = new HashMap();
        map.put("message", "冻结成功!");
        return map;

    }

    /**
     * 用户解冻
     */
    public Map userUnfreeze(Map params) {
        //构造redis key
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        //将redis的冻结信息删除
        redisTemplate.delete(key);
        Map retMap = new HashMap();
        retMap.put("message", "解冻成功");
        return retMap;

    }
}
